package com.nxw.springcloud.gateway.config;

import com.alibaba.fastjson.JSON;
import com.nxw.springcloud.gateway.entity.CommonConstants;
import com.nxw.springcloud.gateway.entity.RateLimitKey;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class RateKeyResolver implements KeyResolver {

    public static final String BEAN_NAME = "rateKeyResolver";

    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        return Mono.just(getKey(exchange));
    }

    /**
     * @param exchange
     * @return
     */
    private String getKey(ServerWebExchange exchange) {

        RateLimitKey rateLimitKey = new RateLimitKey();

        rateLimitKey.setClientIp(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
        String appKey = exchange.getRequest().getHeaders().getFirst(CommonConstants.APP_KEY);
        String appSecret = exchange.getRequest().getHeaders().getFirst(CommonConstants.APP_SECRET);
        String environment = exchange.getRequest().getHeaders().getFirst(CommonConstants.ENVIRONMENT);
        rateLimitKey.setAppKey(appKey + "#" + appSecret+"#"+environment);

        return JSON.toJSONString(rateLimitKey);
    }

}